package com.nineclock.message.service.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.mesaage.dto.NcMessageDTO;
import com.nineclock.mesaage.pojo.NcMessage;
import com.nineclock.message.config.JPushManager;
import com.nineclock.message.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 小康
 * @CreateTime: 2021-06-15 12:18
 * @Description:
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private JPushManager jPushManager;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {
        //1. 保存推送消息
        mongoTemplate.save(message);
        //2. 推送消息
        return jPushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(), null);
    }
/**
 *  @Date: 2021/6/17 10:15
 *  查询推送消息记录
 */
    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {
        //根据传递的参数组装查询条件
        Query query = new Query();
        if(messageDTO == null){
            messageDTO = new NcMessageDTO();
        }

        if(StrUtil.isNotEmpty(messageDTO.getId())){
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }
        if(StrUtil.isNotEmpty(messageDTO.getType())){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }
        if(messageDTO.getUserId()!= null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }
        if(messageDTO.getTargetId() != null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }

        //排序, 根据审核状态升序排序（必须排序，否则会不显示）
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));

        //根据条件查询消息
        List<NcMessage> ncMessages = mongoTemplate.find(query, NcMessage.class);
        return ncMessages;
    }
    @Override
    public void updateMessageWithApproved(String msgId) {


        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(msgId));

        Update update = new Update();
        update.set("useStatus",1);
        update.set("approveStatue",1);

        mongoTemplate.updateFirst(query, update, NcMessage.class);
    }
}
